﻿using Iot.Device.Pn532;
using Iot.Device.Sht3x;
using IotDeviceToolHepler;

using IotDeviceToolHepler.Model.Device;
using IotDeviceToolHepler.Utils;
using Models.Common;
using Models.Device;
using Models.TaskPlain;
using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Device.I2c;
using System.Drawing.Drawing2D;
using System.IO.Ports;
using System.Text;
using System.Threading;
using UnitsNet;
using static Models.Common.EnumDeviceState;
using System.Threading.Tasks;
using GatewayClient.MQ;
using Microsoft.Extensions.Logging;
using Iot.Device.Ht1632;
using UtilsBase;
using UtilsCache;
using UtilsMQ;
using GatewayClient.Models;

namespace GatewayClient.Service
{
    public class ServiceHandleRS485CallBack
    {

        //        配置例子
        //{"agreementType":"rs485","agreementParameter":{"portName":"/dev/ttyS3","baudRate":"9600","command":[{"name":"光强度","key":"light","value":"04 03 00 03 00 01 74 5F"},{"name":"二氧化碳","key":"co2","value":"04 03 00 02 00 01 25 9F"},{ "name":"温度和湿度","key":"temperatureANDhumidity","value":"04 03 00 00 00 02 C4 5E"},{ "name":"二氧化碳回调","key":"startCallBackco2","callBackStart":"true","callBackKey":"co2","callBackKeyName":"二氧化碳","callBackRunInterval":3000,"value":"04 03 00 02 00 01 25 9F"},{ "name":"二氧化碳停止回调","key":"stopCallBackco2","callBackStop":"true","callBackKey":"co2","callBackKeyName":"二氧化碳"},{ "name":"光照度回调","key":"startCallBacklight","callBackStart":"true","callBackKey":"light","callBackKeyName":"光照度","callBackRunInterval":3000,"value":"04 03 00 03 00 01 74 5F"},{ "name":"光照度停止回调","key":"stopCallBacklight","callBackStop":"true","callBackKey":"light","callBackKeyName":"光照度"}]}}

        /// <summary>
        /// 监听事件并回调
        /// </summary>
        /// <param name="obj"></param>
        public void eventListen(MQReqModel<object> mQReqModel)
        {

            CommandLogModel commandLogModel = mQReqModel.toGatewayData;
            try
            {

                ///////////////先响应系统已经收到
                mQReqModel.respCode = ResponseCode.SUCCESS;
                mQReqModel.respMsg = MQEventEnum.Event_State_OK;
                mQReqModel.toServerData = null;
                new ServiceMQ_Helper().sendMsg(mQReqModel);
                ///---------------------处理---------------------------


                ModelCommandAgreement modelCommandAgreement = JsonConvert.DeserializeObject<ModelCommandAgreement>(commandLogModel.parameter);
                ModelCommandAgreementParameter modelCommandAgreementParameter = UtilsObject.DynamicToEntity<ModelCommandAgreementParameter>(modelCommandAgreement.agreementParameter);
                List<ModelCommandAgreementParameterCommand> commandList = UtilsObject.DynamicToEntity<List<ModelCommandAgreementParameterCommand>>(modelCommandAgreement.agreementParameter.command);
                ModelCommandAgreementParameterCommand command = commandList.Where(c => c.key == commandLogModel.key).FirstOrDefault();


                //回传时，只认key
                commandLogModel.key = command.callBackKey;
                //获取自定义令
                if (!string.IsNullOrEmpty(command.value))
                {
                    commandLogModel.content = command.value;
                }
                mQReqModel.toGatewayData = commandLogModel;



                if (command != null)
                {

                    //判断
                    string isRuned = UtilMemoryCacheHelper.get<string>("isCallBacking" + commandLogModel.d_guid + command.callBackKey);
                    if (!string.IsNullOrEmpty(isRuned))
                    {
                        //已经存在，退出
                        return;
                    }

                    //生成缓存
                    UtilMemoryCacheHelper.set("isCallBacking" + commandLogModel.d_guid + command.callBackKey, "runing");

                    //  double valueChange = 0;//值改变
                    bool hasStatusChange = false;//条件改变> 、 <,,true满足当前要求的条件，false不满足当前监听条件
                    //回调处理，一个网关处理一个，，如果想停止，加一个缓存 标识，下发停止指令，判断标识是否继续进行
                    while (true)
                    {

                        //判断
                        string isRuning = UtilMemoryCacheHelper.get<string>("isCallBacking" + commandLogModel.d_guid + command.callBackKey);
                        if (string.IsNullOrEmpty(isRuning))
                        {
                            //已经删除，退出
                            break;
                        }
                        mQReqModel.respMsg = DateTime.Now.ToString("HH:mm:ss.fff");
                        ModelRS485Queue parameter = new ModelRS485Queue();
                        parameter.portName = modelCommandAgreementParameter.portName;
                        parameter.baudRate = modelCommandAgreementParameter.baudRate;
                        parameter.sendData = commandLogModel.content;
                        parameter.content = mQReqModel;
                        ServiceThreadChannelForSerial.writeChannel(JsonConvert.SerializeObject(parameter));

                        Thread.Sleep(command.callBackRunInterval);
                    }
                }
            }
            catch (Exception ex)
            {
                ModelReceverData modelDeviceData = new ModelReceverData();
                modelDeviceData.content = ex.ToString();
                mQReqModel.respCode = ResponseCode.System_ERROR;
                mQReqModel.respMsg = MQEventEnum.Event_State_Error;
                mQReqModel.toServerData = modelDeviceData;
                new ServiceMQ_Helper().sendMsg(mQReqModel);
                Console.WriteLine(ex.ToString());
            }
        }


        public void stopEventListen(MQReqModel<object> mQReqModel)
        {
            //MQReqModel<object> mQReqModel = (MQReqModel<object>)obj;
            CommandLogModel commandLogModel = mQReqModel.toGatewayData;
            try
            {
                ModelCommandAgreement modelCommandAgreement = JsonConvert.DeserializeObject<ModelCommandAgreement>(commandLogModel.parameter);
                List<ModelCommandAgreementParameterCommand> commandList = UtilsObject.DynamicToEntity<List<ModelCommandAgreementParameterCommand>>(modelCommandAgreement.agreementParameter.command);
                ModelCommandAgreementParameterCommand command = commandList.Where(c => c.key == commandLogModel.key).FirstOrDefault();

                //删除缓存
                UtilMemoryCacheHelper.remove("isCallBacking" + commandLogModel.d_guid + command.callBackKey);


                ///////////////先响应系统已经收到
                mQReqModel.respCode = ResponseCode.SUCCESS;
                mQReqModel.respMsg = MQEventEnum.Event_State_OK;
                mQReqModel.toServerData = null;
                new ServiceMQ_Helper().sendMsg(mQReqModel);

            }
            catch (Exception ex)
            {
                ModelReceverData modelDeviceData = new ModelReceverData();
                modelDeviceData.content = ex.ToString();
                mQReqModel.respCode = ResponseCode.System_ERROR;
                mQReqModel.respMsg = MQEventEnum.Event_State_Error;
                mQReqModel.toServerData = modelDeviceData;
                new ServiceMQ_Helper().sendMsg(mQReqModel);
                Console.WriteLine(ex.ToString());
            }
        }
    }

}
